// compress.js
Page({
  data: {
    imagePath: '',
    compressedImagePath: '',
    compressing: false,
    compressionRate: 80, // 默认压缩率
    originalSize: 0,
    compressedSize: 0,
    compressionPercent: '--' // 压缩百分比
  },

  onLoad() {
    console.log('图片压缩页面加载');
  },

  // 选择图片
  chooseImage() {
    wx.chooseMedia({
      count: 1,
      mediaType: ['image'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        const tempFilePath = res.tempFiles[0].tempFilePath;
        const fileSize = res.tempFiles[0].size;
        
        this.setData({
          imagePath: tempFilePath,
          originalSize: fileSize,
          compressedImagePath: '',
          compressedSize: 0
        });
        
        console.log('选择的图片：', tempFilePath);
        console.log('原始大小：', this.formatFileSize(fileSize));
      }
    });
  },

  // 调整压缩率
  sliderChange(e) {
    this.setData({
      compressionRate: e.detail.value
    });
  },

  // 压缩图片
  compressImage() {
    if (!this.data.imagePath) {
      wx.showToast({
        title: '请先选择图片',
        icon: 'none'
      });
      return;
    }

    this.setData({
      compressing: true
    });

    // 使用canvas进行图片压缩
    const quality = this.data.compressionRate / 100;
    
    wx.getImageInfo({
      src: this.data.imagePath,
      success: (res) => {
        const canvasId = 'compressCanvas';
        const ctx = wx.createCanvasContext(canvasId);
        
        const canvasWidth = res.width;
        const canvasHeight = res.height;
        
        // 设置canvas尺寸
        this.setData({
          canvasWidth: canvasWidth,
          canvasHeight: canvasHeight
        });
        
        // 绘制图片到canvas
        ctx.drawImage(this.data.imagePath, 0, 0, canvasWidth, canvasHeight);
        ctx.draw(false, () => {
          // 将canvas导出为图片
          wx.canvasToTempFilePath({
            canvasId: canvasId,
            fileType: 'jpg',
            quality: quality,
            success: (result) => {
              // 获取压缩后图片信息
              wx.getFileInfo({
                filePath: result.tempFilePath,
                success: (sizeRes) => {
                  const compressionPercent = ((sizeRes.size / this.data.originalSize) * 100).toFixed(1);
                  this.setData({
                    compressedImagePath: result.tempFilePath,
                    compressedSize: sizeRes.size,
                    compressionPercent: compressionPercent,
                    compressing: false
                  });
                  
                  console.log('压缩后大小：', this.formatFileSize(sizeRes.size));
                  console.log('压缩率：', (sizeRes.size / this.data.originalSize * 100).toFixed(2) + '%');
                  
                  wx.showToast({
                    title: '压缩成功',
                    icon: 'success'
                  });
                }
              });
            },
            fail: (err) => {
              console.error('压缩失败：', err);
              this.setData({
                compressing: false
              });
              
              wx.showToast({
                title: '压缩失败，请重试',
                icon: 'none'
              });
            }
          });
        });
      },
      fail: (err) => {
        console.error('获取图片信息失败：', err);
        this.setData({
          compressing: false
        });
        
        wx.showToast({
          title: '获取图片信息失败',
          icon: 'none'
        });
      }
    });
  },

  // 保存压缩后的图片
  saveImage() {
    if (!this.data.compressedImagePath) {
      wx.showToast({
        title: '请先压缩图片',
        icon: 'none'
      });
      return;
    }

    wx.saveImageToPhotosAlbum({
      filePath: this.data.compressedImagePath,
      success: () => {
        wx.showToast({
          title: '保存成功',
          icon: 'success'
        });
      },
      fail: (err) => {
        console.error('保存失败：', err);
        
        if (err.errMsg.indexOf('auth deny') >= 0) {
          wx.showModal({
            title: '提示',
            content: '需要您授权保存图片到相册',
            confirmText: '去授权',
            success: (res) => {
              if (res.confirm) {
                wx.openSetting({
                  success: (settingRes) => {
                    console.log('设置结果：', settingRes);
                  }
                });
              }
            }
          });
        } else {
          wx.showToast({
            title: '保存失败',
            icon: 'none'
          });
        }
      }
    });
  },

  // 格式化文件大小
  formatFileSize(size) {
    if (size < 1024) {
      return size + 'B';
    } else if (size < 1024 * 1024) {
      return (size / 1024).toFixed(2) + 'KB';
    } else {
      return (size / (1024 * 1024)).toFixed(2) + 'MB';
    }
  }
});
